<?php

namespace AdminModule\Models;

class Authenticator extends \Nette\Object implements \Nette\Security\IAuthenticator {

    /** @var Nette\Database\Connection */
    private $database;

    public function __construct(\Nette\Database\Connection $database) {
        $this->database = $database;
    }

    /**
     * Performs an authentication.
     * @return Nette\Security\Identity
     * @throws Nette\Security\AuthenticationException
     */
    public function authenticate(array $credentials) {
        list($username, $password) = $credentials;
        $row = $this->database->table('users')->where('username', $username)->fetch();

        if (!$row) {
            throw new \Nette\Security\AuthenticationException('Špatně zadané uživatelské jméno.', self::IDENTITY_NOT_FOUND);
        }

        if ($row->password !== $this->calculateHash($password, $row->username)) {
            throw new \Nette\Security\AuthenticationException('Špatně zadané heslo.', self::INVALID_CREDENTIAL);
        }

        unset($row->password);
        return new \Nette\Security\Identity($row->id_user, $row->role, $row->toArray());
    }

    /**
     * Computes salted password hash.
     * 
     * @param type $password
     * @param type $salt
     */
    public function calculateHash($password, $salt) {        
        $hash = sha1($password . str_repeat(substr($salt, 0, 3), 5));
//        \Nette\Diagnostics\Debugger::dump($hash);
        return $hash;
    }

}
